/*
 * @Author: ljk
 * @Date: 2023-05-11 20:23:54
 * @LastEditors: ljk
 * @LastEditTime: 2023-05-12 13:23:04
 * @Description: 命名管道服务端
 */
#include "comm.hpp"

int main()
{
    // 1. 创建管道文件,一次就行
    umask(0);
    int n = mkfifo(fifoname.c_str(), mode);
    if (n != 0)
    {
        std::cout << errno << " : " << strerror(errno) << std::endl;
        return 1;
    }

    // 2. 让服务端开启管道文件 -- 一开始在此处卡住
    std::cout << "create fifo file success, wait client open file..." << std::endl;
    int rfd = open(fifoname.c_str(), O_RDONLY);
    if (rfd < 0)
    {
        std::cout << errno << " : " << strerror(errno) << std::endl;
        return 2;
    }
    std::cout << "open fifo sucess, begin ipc" << std::endl;

    // 3. 正常通信
    char buffer[NUM];
    while (true)
    {
        buffer[0] = 0;
        ssize_t n = read(rfd, buffer, sizeof(buffer) - 1);
        if (n > 0)
        {
            buffer[n] = 0;
            //std::cout << "client: " << buffer << std::endl;
            printf("%c", buffer[0]);
            fflush(stdout);
        }
        else if (n == 0)
        {
            std::cout << "client quit, me too" << std::endl;
            break;
        }
        else
        {
            std::cout << errno << " : " << strerror(errno) << std::endl;
            break;
        }
    }
    //关闭不要的fd
    close(rfd);
    //通信完成后清除管道文件
    unlink(fifoname.c_str());
    return 0;
}